package com.mmloo.common.controller;



import com.mmloo.common.message.Message;
import com.mmloo.common.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/images")
public class ImageController {


    @Autowired
    BaseService baseService;

    /**
     * 图片上传
     * @param request

     * @return
     */
    /*@ResponseBody
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public String upload(@RequestParam("mediaFile") MultipartFile multipartFile,HttpServletRequest request,HttpServletResponse response){
        String path = request.getServletContext().getRealPath("/");

       *//* System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> files  = multipartRequest.getFiles("uploadFiles");
        CommonsMultipartFile[] commonsMultipartFiles=new CommonsMultipartFile[files.size()];
        for (int i=0;i<files.size();i++){
            commonsMultipartFiles[i]=(CommonsMultipartFile)files.get(i);
        }
        String path=request.getSession().getServletContext().getRealPath("");
        ImageManager manager=new ImageManager();

        List<String> imageUrls=new ArrayList<>();
        if (commonsMultipartFiles.length!=0) {
            imageUrls=manager.upload(commonsMultipartFiles, path);
        }

        Message message;
        if (imageUrls!=null&&!imageUrls.isEmpty()){
            message=new Message(true,"success",imageUrls);
        }else{
            message=new Message(false,"failed");
        }
        return message.toJson();*//*
    }*/

    @ResponseBody
    @RequestMapping(value = "/upload")
    public String uploadMedia(@RequestParam("mediaFile") MultipartFile multipartFile,
                              HttpServletRequest request) throws Exception {
        System.out.println("**********************************************");
        String path = request.getSession().getServletContext().getRealPath("/");
        System.out.println("path =  " + path);
        String result = baseService.handleUploadMedia(path,multipartFile);
        return new Message(true,"",result).toJson();
    }
    /**
     * 图片下载
     * @param url
     * @param response
     * @return
     */
    @RequestMapping(value = "/downLoad.do",method = RequestMethod.POST)
    public void downLoad(@RequestParam(value = "url") String url,HttpServletResponse response){
        File file = new File(url);
        FileInputStream input = null;
        OutputStream output = null;
        response.setContentType("text/html;charset =utf-8");
//        response.setHeader("Access-Control-Allow-Origin","*");
        try {
            response.setHeader("Content-Disposition", "attachment;filename="+java.net.URLEncoder.encode(file.getName(), "UTF-8"));
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        long fileLenght = file.length();
        byte[] buffer = new byte[1024];
        try {
            input = new FileInputStream(file);
            output = response.getOutputStream();
            int len = 0;
            while((len = input.read(buffer,0 , buffer.length))!=-1){
                output.write(buffer, 0, len);
            }

            output.flush();

        } catch (FileNotFoundException e) {

            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally{
            try {
                if(output!=null){
                    output.close();
                    output=null;
                }
                if(input!=null)
                    input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
